import re


from django import http
from django.contrib.auth import login
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View

from apps.user.models import User
from utils.response_code import RETCODE


class RegisterView(View):
    def get(self,request):
        return render(request,'register.html')
    def post(self,request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')
        if not all([username,password,password2,mobile,allow]):
            return http.HttpResponseBadRequest('缺少必传参数')
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return http.HttpResponseBadRequest('请输入5-20位帐号')
        if not re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return http.HttpResponseBadRequest('请输入8-20位密码')
        if not password == password2:
            return http.HttpResponseBadRequest('请重新确认密码')
        if not re.match(r'^1[345789]\d{9}$',mobile):
            return http.HttpResponseBadRequest('请输入正确的手机号')
        if not allow =='on':
            return http.HttpResponseBadRequest('请勾选协议')
        try:
            user = User.objects.create_user(username=username,password=password,mobile=mobile)
        except:
            login(request,user)
            return http.HttpResponseBadRequest('数据库未打开')
        return redirect(reverse('contents:index'))
class UsernameCountView(View):
    def get(self,request,username):

        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'count': count})
class MobileCountView(View):
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'mobile':mobile})

